import requests
import json
import hashlib
from time import time
from flask import current_app
from app import executor, redisclient
from app.api.v1 import tb_orders
from app.libs.enums import ERROR_CODE
from app.libs.error_code import ParameterException
from app.models.order_info import order_info
from app.taobao_api import config
from app.models.base import db
from app.taobao_api.update_order_status import Logistics_Dummy_Send
from app.models.taobao_orders import taobao_orders


class Order_Status():
    def __init__(self, tid, sum, token, char_sum=0):
        self.url = config.ORDER_INFO_URL
        self.tid = tid
        self.tids = tid.split(',')
        self.sum = sum
        self.char_sum = char_sum
        self.appsecret = config.APPSECRET
        self.token = token
        self.headers = {
            'Authorization': 'Bearer ' + token,
            'ApiVersion': '1'
        }
        self.tmp_headers = {
            'Authorization': 'Bearer ' + 'TbAlds22fd5289bkd92ucpdwffkumw8az8bys577fu43b7gmsw',
            'ApiVersion': '1'
        }

    def signstr(self, pre_body):  # 签名算法
        sign_str = self.appsecret
        for key, value in pre_body.items():
            sign_str += key + value
        sign_str += self.appsecret
        md5 = hashlib.md5()
        md5.update(sign_str.encode('utf-8'))
        return md5.hexdigest()

    def tidInfo(self, tid):
        current_time = str(int(time()))
        pre_body = {
            'tid': tid,
            'timestamp': current_time
        }
        body = {
            'tid': tid,
            'timestamp': current_time,
            'sign': self.signstr(pre_body)
        }
        try:
            r = requests.post(self.url, headers=self.headers, data=body)
            print(r.text)
        except Exception as e:
            error_info = ERROR_CODE[-2] + str(e)
            raise ParameterException(msg=[error_info])
        dictinfo = json.loads(r.text)
        if dictinfo['Error_Code'] == 0:
            result = {
                'shop': dictinfo['Data']['SellerNick'],
                'amount': dictinfo['Data']['Payment'],
                'num': dictinfo['Data']['Num'],
                'status': dictinfo['Data']['Status'],
                'sku_id': dictinfo['Data']['Orders'][0]['SkuId'] if 'SkuId' in dictinfo['Data']['Orders'][
                    0].keys() else '',
                'buyer': dictinfo['Data']['BuyerOpenUid'],
                'sku_name': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in
                                                                            dictinfo['Data']['Orders'][
                                                                                0].keys() else ''
            }
            print(result)
            return result
        else:
            return {}
    
    def validate_aigc_tid(self):
        current_time = str(int(time()))
        tids = []
        nums = 0
        shop = ''
        amount = 0
        if ',' in self.tid:
            tids = self.tid.split(",")
        else:
            tids.append(self.tid)
        taobao_order_info = taobao_orders.query.filter_by(order_number=tids[0]).first()
        if taobao_order_info:
            if taobao_order_info.type == 'aigc':
                nums = taobao_order_info.remain
                if self.sum <= nums:
                    with db.auto_commit():
                        db.session.query(taobao_orders).filter(taobao_orders.order_number == tids[0]).update(
                            {'remain': taobao_orders.remain - self.sum})
                    return True
            elif taobao_order_info.type == 'aigc+vip':
                if taobao_order_info.remain<1:
                    raise ParameterException(msg=['订单数量不足'])
                with db.auto_commit():
                    db.session.query(taobao_orders).filter(taobao_orders.order_number == tids[0]).update(
                        {'remain': taobao_orders.remain - 1})
                    return True
            else:
                raise ParameterException(msg=['该订单号不适用于AIGC检测'])
        else:
            for tid in tids:
                pre_body = {
                    'tid': tid,
                    'timestamp': current_time
                }
                body = {
                    'tid': tid,
                    'timestamp': current_time,
                    'sign': self.signstr(pre_body)
                }
                try:
                    r = requests.post(self.url, headers=self.headers, data=body)
                except Exception as e:
                    error_info = ERROR_CODE[-2] + str(e)
                    raise ParameterException(msg=[error_info])
                dictinfo = json.loads(r.text)
                if dictinfo['Error_Code'] == 0:
                    result = {
                        'shop': dictinfo['Data']['SellerNick'],
                        'amount': dictinfo['Data']['Payment'],
                        'num': dictinfo['Data']['Num'],
                        'status': dictinfo['Data']['Status'],
                        'sku_id': dictinfo['Data']['Orders'][0]['SkuId'] if 'SkuId' in dictinfo['Data']['Orders'][0].keys() else '',
                        'sku_name': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in dictinfo['Data']['Orders'][0].keys() else ''
                    }
                    if result['status'] in ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS']:
                        if 'AIGC' not in result['sku_name']:
                            raise ParameterException(msg=['该订单号不适用于AIGC检测服务'])
                        if '不限字数' in result['sku_name']:
                            if '37篇' in result['sku_name']:
                                with db.auto_commit():
                                    taobao_order = taobao_orders()
                                    taobao_order.order_number = tids[0]
                                    taobao_order.order_detail = self.tid
                                    taobao_order.remain = 37 * result['num'] - 1
                                    taobao_order.total = 37 * result['num']
                                    taobao_order.shop = result['shop']
                                    taobao_order.amount = result['amount']
                                    taobao_order.type = 'aigc+vip'
                                    db.session.add(taobao_order)
                                return True
                        nums += result['num']
                        amount += float(result['amount'])
                        shop = result['shop']
                    else:
                        raise ParameterException(msg=[ERROR_CODE[-3] + '订单号 ' + tid + ' 状态不正确，请确认该订单是否已完成！'])
            if nums < self.sum:
                raise ParameterException(msg=[ERROR_CODE[-1]])     
            else:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = tids[0]
                    taobao_order.order_detail = self.tid
                    taobao_order.remain = nums - self.sum
                    taobao_order.total = nums
                    taobao_order.shop = shop
                    taobao_order.amount = amount
                    taobao_order.type = 'aigc'
                    db.session.add(taobao_order)
                return True
    
    def validate_check_ai_tid_new(self):
        text_check_remain = 0
        ai_check_remain = 0
        text_check_unlimit_remain = 0
        ai_check_unlimit_remain = 0
        for tid in self.tids:
            taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
            if not taobao_order_info:
                self.insert_order(tid)
                taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
            text_check_remain += taobao_order_info.text_check_remain
            ai_check_remain += taobao_order_info.ai_check_remain
            text_check_unlimit_remain += taobao_order_info.text_check_unlimit_remain
            ai_check_unlimit_remain += taobao_order_info.ai_check_unlimit_remain
        if ai_check_unlimit_remain > 0:
            for tid in self.tids:
                with db.auto_commit():
                    taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
                    if taobao_order_info.ai_check_unlimit_remain > 0:
                        taobao_orders.query.filter_by(order_number=tid).update({
                            'ai_check_unlimit_remain': taobao_orders.ai_check_unlimit_remain - 1
                        })
                        return True
            return True
        
    def validate_order_number(self, check_type):
        text_check_remain = 0
        ai_check_remain = 0
        text_check_unlimit_remain = 0
        ai_check_unlimit_remain = 0
        for tid in self.tids:
            taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
            if not taobao_order_info:
                self.insert_order(tid)
                taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
            text_check_remain += taobao_order_info.text_check_remain
            ai_check_remain += taobao_order_info.ai_check_remain
            text_check_unlimit_remain += taobao_order_info.text_check_unlimit_remain
            ai_check_unlimit_remain += taobao_order_info.ai_check_unlimit_remain
        if check_type == 'text_check':
            if text_check_remain == 0 and text_check_unlimit_remain == 0:
                raise ParameterException(msg=['提交失败，订单类型错误或数量不足'])
            if text_check_unlimit_remain > 0:
                for tid in self.tids:
                    with db.auto_commit():
                        taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
                        if taobao_order_info.text_check_unlimit_remain > 0:
                            taobao_orders.query.filter_by(order_number=tid).update({
                                'text_check_unlimit_remain': taobao_orders.text_check_unlimit_remain - 1
                            })
                            return True
                return True
            else:
                if self.sum > text_check_remain:
                    raise ParameterException(msg=[ERROR_CODE[-1]])
                else:
                    for tid in self.tids:
                        with db.auto_commit():
                            taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
                            if taobao_order_info.text_check_remain-self.sum >= 0:
                                taobao_orders.query.filter_by(order_number=tid).update({
                                    'text_check_remain': taobao_orders.text_check_remain - self.sum
                                })
                                return True
                            else:
                                taobao_orders.query.filter_by(order_number=tid).update({
                                    'text_check_remain': 0
                                })
                                self.sum = self.sum - taobao_order_info.text_check_remain
                    return True
        if check_type == 'aigc':
            if ai_check_remain == 0 and ai_check_unlimit_remain == 0:
                raise ParameterException(msg=['提交失败，订单类型错误或数量不足'])
            if ai_check_unlimit_remain > 0:
                for tid in self.tids:
                    with db.auto_commit():
                        taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
                        if taobao_order_info.ai_check_unlimit_remain > 0:
                            taobao_orders.query.filter_by(order_number=tid).update({
                                'ai_check_unlimit_remain': taobao_orders.ai_check_unlimit_remain - 1
                            })
                            return True
                return True
            else:
                if self.sum > ai_check_remain:
                    raise ParameterException(msg=[ERROR_CODE[-1]])
                else:
                    for tid in self.tids:
                        with db.auto_commit():
                            taobao_order_info = taobao_orders.query.filter_by(order_number=tid).first()
                            if taobao_order_info.ai_check_remain-self.sum >= 0:
                                taobao_orders.query.filter_by(order_number=tid).update({
                                    'ai_check_remain': taobao_orders.ai_check_remain - self.sum
                                })
                                return True
                            else:
                                taobao_orders.query.filter_by(order_number=tid).update({
                                    'ai_check_remain': 0
                                })
                                self.sum = self.sum - taobao_order_info.ai_check_remain
                    return True

    def getOrderFrom(self, order_number):
        current_time = str(int(time()))
        pre_body = {
                        'tid': order_number,
                        'timestamp': current_time
                    }
        body = {
            'tid': order_number,
            'timestamp': current_time,
            'sign': self.signstr(pre_body)
        }
        try:
            r = requests.post(self.url, headers=self.headers, data=body)
        except Exception as e:
            error_info = ERROR_CODE[-2] + str(e)
            raise ParameterException(msg=[error_info])
        dictinfo = json.loads(r.text)
        if dictinfo['Error_Code'] == 0:
            result = {
                'shop': dictinfo['Data']['SellerNick'],
                'amount': dictinfo['Data']['Payment'],
                'num': dictinfo['Data']['Num'],
                'status': dictinfo['Data']['Status'],
                'sku_id': dictinfo['Data']['Orders'][0]['SkuId'] if 'SkuId' in
                                                                    dictinfo['Data']['Orders'][
                                                                        0].keys() else '',
                'sku_name': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in
                                                                    dictinfo['Data']['Orders'][
                                                                        0].keys() else ''
            }
            return result
        else:
            try:
                r = requests.post(self.url, headers=self.tmp_headers, data=body)
            except Exception as e:
                error_info = ERROR_CODE[-2] + str(e)
                raise ParameterException(msg=[error_info])
            dictinfo = json.loads(r.text)
            if dictinfo['Error_Code'] == 0:
                result = {
                    'shop': dictinfo['Data']['SellerNick'],
                    'amount': dictinfo['Data']['Payment'],
                    'num': dictinfo['Data']['Num'],
                    'status': dictinfo['Data']['Status'],
                    'sku_id': dictinfo['Data']['Orders'][0]['SkuId'] if 'SkuId' in
                                                                        dictinfo['Data']['Orders'][
                                                                            0].keys() else '',
                    'sku_name': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in
                                                                        dictinfo['Data']['Orders'][
                                                                            0].keys() else ''
                }
                return result
            else:
                raise ParameterException(msg=[ERROR_CODE[dictinfo['Error_Code']]])
        
    def insert_order(self, order_number):
        result = self.getOrderFrom(order_number=order_number)
        if result['status'] in ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS','TRADE_FINISHED']:
            sku_name = result['sku_name'].replace(' ', '')
            if '个人查重次数版' in result['sku_name'] and 'AIGC' not in result['sku_name']:
                total = 0
                if '37' in sku_name:
                    total = 37
                if '365' in sku_name:
                    total = 365
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_unlimit_remain = total
                    taobao_order.total = total * result['num']
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif '37篇AIGC个人查重次数版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.ai_check_unlimit_remain = 37
                    taobao_order.total = 37
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif '37篇查重个人版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_unlimit_remain = 37
                    taobao_order.total = 37
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif '37篇查重次数版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_unlimit_remain = 37
                    taobao_order.total = 37
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif '365篇查重次数版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_unlimit_remain = 365
                    taobao_order.total = 365
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif '37篇查重个人版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_unlimit_remain = 37
                    taobao_order.total = 37
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif '365篇查重个人版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_unlimit_remain = 365
                    taobao_order.total = 365
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'vip'
                    db.session.add(taobao_order)
            elif 'AIGC查重专用' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.ai_check_remain = result['num']
                    taobao_order.total = result['num']
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'aigc'
                    db.session.add(taobao_order)
            elif 'AIGC检测专用' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.ai_check_remain = result['num']
                    taobao_order.total = result['num']
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'aigc'
                    db.session.add(taobao_order)
            elif '+aigc检测' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.ai_check_remain = result['num']
                    taobao_order.text_check_remain = result['num']
                    taobao_order.total = result['num']
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = '+aigc'
                    db.session.add(taobao_order)
            elif 'AIGC个人查重次数版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.ai_check_unlimit_remain = result['num'] *37
                    taobao_order.total = result['num'] *37
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = '+aigc'
                    db.session.add(taobao_order)
            elif '37篇AIGC+普通查重合并个人查重次数版' in sku_name:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.ai_check_unlimit_remain = result['num'] *37
                    taobao_order.text_check_unlimit_remain = result['num'] *37
                    taobao_order.total = result['num'] *37
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = '+aigc'
                    db.session.add(taobao_order)
            else:
                with db.auto_commit():
                    taobao_order = taobao_orders()
                    taobao_order.order_number = order_number
                    taobao_order.order_detail = order_number
                    taobao_order.text_check_remain = result['num']
                    taobao_order.total = result['num']
                    taobao_order.shop = result['shop']
                    taobao_order.amount = result['amount']
                    taobao_order.type = 'normal'
                    db.session.add(taobao_order)
            return taobao_order
        else:
            raise ParameterException(msg=[ERROR_CODE[-3] + '订单号 ' + order_number + ' 状态不正确，请确认该订单是否已完成！'])

    def validate_tid(self):  # 验证订单号
        current_time = str(int(time()))
        tids = []
        nums = 0
        shop = ''
        amount = 0
        if ',' in self.tid:
            tids = self.tid.split(",")
        else:
            tids.append(self.tid)
        taobao_order_info = taobao_orders.query.filter_by(order_number=tids[0]).first()
        if taobao_order_info:
            if taobao_order_info.type == 'normal':
                article_info = order_info.query.filter_by(taobao_orders=tids[0]).first()
                if not article_info:
                    return True
                nums = taobao_order_info.remain
                if self.sum <= nums:
                    with db.auto_commit():
                        db.session.query(taobao_orders).filter(taobao_orders.order_number == tids[0]).update(
                            {'remain': taobao_orders.remain - self.sum})
                    return True
                elif nums == 0:
                    raise ParameterException(msg=[ERROR_CODE[-4]])
                else:
                    raise ParameterException(msg=[ERROR_CODE[-1]])
            if taobao_order_info.type == 'vip':
                if taobao_order_info.remain < 1:
                    raise ParameterException(msg=['该订单号额度已用完,请重新购买'])
                articles = order_info.query.filter_by(taobao_orders=tids[0]).filter_by(completed=0).all()
                if len(articles) > 4:
                    raise ParameterException(msg=['订单号有正在进行的任务，请任务完成后继续提交'])
                with db.auto_commit():
                    db.session.query(taobao_orders).filter(taobao_orders.order_number == tids[0]).update(
                        {'remain': taobao_orders.remain - 1})
                return True
            else:
                raise ParameterException(msg=['订单类型不正确'])
        else:
            freecode = redisclient.freecode()
            if tids[0][0:8] != freecode:
                for tid in tids:
                    pre_body = {
                        'tid': tid,
                        'timestamp': current_time
                    }
                    body = {
                        'tid': tid,
                        'timestamp': current_time,
                        'sign': self.signstr(pre_body)
                    }
                    try:
                        r = requests.post(self.url, headers=self.headers, data=body)
                    except Exception as e:
                        error_info = ERROR_CODE[-2] + str(e)
                        raise ParameterException(msg=[error_info])
                    dictinfo = json.loads(r.text)
                    if dictinfo['Error_Code'] == 0:
                        result = {
                            'shop': dictinfo['Data']['SellerNick'],
                            'amount': dictinfo['Data']['Payment'],
                            'num': dictinfo['Data']['Num'],
                            'status': dictinfo['Data']['Status'],
                            'sku_id': dictinfo['Data']['Orders'][0]['SkuId'] if 'SkuId' in
                                                                                dictinfo['Data']['Orders'][
                                                                                    0].keys() else '',
                            'sku_name': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in
                                                                                dictinfo['Data']['Orders'][
                                                                                    0].keys() else ''
                        }
                        if result['status'] in ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS']:
                            if result['sku_id'] == '5082305780383':
                                if self.char_sum > 7000:
                                    raise ParameterException(
                                        msg=[ERROR_CODE[-3] + '订单号 ' + tid + '只可用于6000字符以内的小论文'])
                            if '不限字数' in result['sku_name']:
                                if '37篇' in result['sku_name']:
                                    with db.auto_commit():
                                        taobao_order = taobao_orders()
                                        taobao_order.order_number = tids[0]
                                        taobao_order.order_detail = self.tid
                                        taobao_order.remain = 37 * result['num'] - 1
                                        taobao_order.total = 37 * result['num']
                                        taobao_order.shop = result['shop']
                                        taobao_order.amount = result['amount']
                                        taobao_order.type = 'vip'
                                        db.session.add(taobao_order)
                                    return True
                                if '365篇' in result['sku_name']:
                                    with db.auto_commit():
                                        taobao_order = taobao_orders()
                                        taobao_order.order_number = tids[0]
                                        taobao_order.order_detail = self.tid
                                        taobao_order.remain = 365 * result['num'] - 1
                                        taobao_order.total = 365 * result['num']
                                        taobao_order.shop = result['shop']
                                        taobao_order.amount = result['amount']
                                        taobao_order.type = 'vip'
                                        db.session.add(taobao_order)
                                    return True
                            else:
                                nums += result['num']
                                amount += float(result['amount'])
                                shop = result['shop']
                                sku_name = result['sku_name']
                        else:
                            raise ParameterException(
                                msg=[ERROR_CODE[-3] + '订单号 ' + tid + ' 状态不正确，请确认该订单是否已完成！'])
                    else:
                        try:
                            r = requests.post(self.url, headers=self.tmp_headers, data=body)
                        except Exception as e:
                            error_info = ERROR_CODE[-2] + str(e)
                            raise ParameterException(msg=[error_info])
                        dictinfo = json.loads(r.text)
                        if dictinfo['Error_Code'] == 0:
                            result = {
                                'shop': dictinfo['Data']['SellerNick'],
                                'amount': dictinfo['Data']['Payment'],
                                'num': dictinfo['Data']['Num'],
                                'status': dictinfo['Data']['Status'],
                                'sku_id': dictinfo['Data']['Orders'][0]['SkuId'] if 'SkuId' in dictinfo['Data']['Orders'][0].keys() else '',
                                'sku_name': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in dictinfo['Data']['Orders'][0].keys() else ''
                            }
                            if result['status'] in ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS']:
                                if result['sku_id'] == '5082305780383':
                                    if self.char_sum > 7000:
                                        raise ParameterException(
                                            msg=[ERROR_CODE[-3] + '订单号 ' + tid + '只可用于6000字符以内的小论文'])
                                if '不限字数' in result['sku_name']:
                                    if '37篇' in result['sku_name']:
                                        with db.auto_commit():
                                            taobao_order = taobao_orders()
                                            taobao_order.order_number = tids[0]
                                            taobao_order.order_detail = self.tid
                                            taobao_order.remain = 37 * result['num'] - 1
                                            taobao_order.total = 37 * result['num']
                                            taobao_order.shop = result['shop']
                                            taobao_order.amount = result['amount']
                                            taobao_order.type = 'vip'
                                            db.session.add(taobao_order)
                                        return True
                                    if '365篇' in result['sku_name']:
                                        with db.auto_commit():
                                            taobao_order = taobao_orders()
                                            taobao_order.order_number = tids[0]
                                            taobao_order.order_detail = self.tid
                                            taobao_order.remain = 365 * result['num'] - 1
                                            taobao_order.total = 365 * result['num']
                                            taobao_order.shop = result['shop']
                                            taobao_order.amount = result['amount']
                                            taobao_order.type = 'vip'
                                            db.session.add(taobao_order)
                                        return True
                                else:
                                    nums += result['num']
                                    amount += float(result['amount'])
                                    shop = result['shop']
                                    sku_name = result['sku_name']
                            else:
                                raise ParameterException(
                                    msg=[ERROR_CODE[-3] + '订单号 ' + tid + ' 状态不正确，请确认该订单是否已完成！'])
                        else:
                            raise ParameterException(msg=[ERROR_CODE[dictinfo['Error_Code']]])
                if nums < self.sum:
                    raise ParameterException(msg=[ERROR_CODE[-1]])
                else:
                    if '+aigc' in sku_name:
                        with db.auto_commit():
                            taobao_order = taobao_orders()
                            taobao_order.order_number = tids[0]
                            taobao_order.order_detail = self.tid
                            taobao_order.remain = nums - self.sum
                            taobao_order.total = nums
                            taobao_order.shop = shop
                            taobao_order.amount = amount
                            taobao_order.type = 'aigc+check'
                            db.session.add(taobao_order)
                            return 'aigc+check'
                    else:
                        with db.auto_commit():
                            taobao_order = taobao_orders()
                            taobao_order.order_number = tids[0]
                            taobao_order.order_detail = self.tid
                            taobao_order.remain = nums - self.sum
                            taobao_order.total = nums
                            taobao_order.shop = shop
                            taobao_order.amount = amount
                            taobao_order.type = 'normal'
                            db.session.add(taobao_order)
                    return True
            else:
                return 9

    def test(self, tid):
        current_time = str(int(time()))
        pre_body = {
            'tid': tid,
            'timestamp': current_time
        }
        body = {
            'tid': tid,
            'timestamp': current_time,
            'sign': self.signstr(pre_body)
        }
        try:
            r = requests.post(self.url, headers=self.headers, data=body)
            print(r.text)
        except Exception as e:
            error_info = ERROR_CODE[-2] + str(e)
            # raise ParameterException(msg=[error_info])

    def validate_tid_for_free(self):  # 验证订单号
        current_time = str(int(time()))
        tids = []
        nums = 0
        shop = ''
        amount = 0
        if ',' in self.tid:
            tids = self.tid.split(",")
        else:
            tids.append(self.tid)
        tb_order_info = taobao_orders.query.filter_by(order_number=tids[0]).first()
        if tb_order_info:
            nums = tb_order_info.remain
            if self.sum <= nums:
                with db.auto_commit():
                    db.session.query(taobao_orders).filter(taobao_orders.order_number == tids[0]).update(
                        {'remain': taobao_orders.remain - self.sum})
                return True
            else:
                article_info = order_info.query.filter_by(taobao_orders=tids[0]).order_by(order_info.id.desc()).first()
                if article_info:
                    if int(time()) - tb_order_info.create_time > 86400 * 3:
                        raise ParameterException(msg=['订单已超过无限查重时效，请重新购买'])
                    if article_info.completed == 0:
                        raise ParameterException(msg=['该订单号存在正在进行中的任务,请任务完成后再提交'])
                return True
        else:
            freecode = redisclient.freecode()
            if tids[0][0:8] != freecode:
                for tid in tids:
                    pre_body = {
                        'tid': tid,
                        'timestamp': current_time
                    }
                    body = {
                        'tid': tid,
                        'timestamp': current_time,
                        'sign': self.signstr(pre_body)
                    }
                    try:
                        r = requests.post(self.url, headers=self.headers, data=body)
                    except Exception as e:
                        error_info = ERROR_CODE[-2] + str(e)
                        raise ParameterException(msg=[error_info])
                    dictinfo = json.loads(r.text)
                    if dictinfo['Error_Code'] == 0:
                        result = {
                            'shop': dictinfo['Data']['SellerNick'],
                            'amount': dictinfo['Data']['Payment'],
                            'num': dictinfo['Data']['Num'],
                            'status': dictinfo['Data']['Status'],
                            'sku': dictinfo['Data']['Orders'][0]['SkuPropertiesName'] if 'SkuPropertiesName' in
                                                                                         dictinfo['Data']['Orders'][
                                                                                             0].keys() else ''
                        }
                        if result['status'] in ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS']:
                            if result['sku'] in ['类型:本科专科定稿专用', '类型:硕士博士定稿专用']:
                                with db.auto_commit():
                                    taobao_order = taobao_orders()
                                    taobao_order.order_number = tids[0]
                                    taobao_order.order_detail = self.tid
                                    taobao_order.remain = 0
                                    taobao_order.total = result['num']
                                    taobao_order.shop = result['shop']
                                    taobao_order.amount = result['amount']
                                    db.session.add(taobao_order)
                                return True
                            else:
                                if float(result['amount']) < 2.7 and result['shop'] != 'samereport教育旗舰店':
                                    raise ParameterException(msg=['订单错误'])
                                nums += result['num']
                                amount += float(result['amount'])
                                shop = result['shop']
                        else:
                            raise ParameterException(
                                msg=[ERROR_CODE[-3] + '订单号 ' + tid + ' 状态不正确，请确认该订单是否已完成！'])
                    else:
                        raise ParameterException(msg=[ERROR_CODE[dictinfo['Error_Code']]])
                if nums < self.sum:
                    with db.auto_commit():
                        taobao_order = taobao_orders()
                        taobao_order.order_number = tids[0]
                        taobao_order.order_detail = self.tid
                        taobao_order.remain = 0
                        taobao_order.total = nums
                        taobao_order.shop = shop
                        taobao_order.amount = amount
                        db.session.add(taobao_order)
                else:
                    with db.auto_commit():
                        taobao_order = taobao_orders()
                        taobao_order.order_number = tids[0]
                        taobao_order.order_detail = self.tid
                        taobao_order.remain = nums - self.sum
                        taobao_order.total = nums
                        taobao_order.shop = shop
                        taobao_order.amount = amount
                        db.session.add(taobao_order)
                    return True
            else:
                return 9


def Logistics(order_number, token, app):
    ctx = app.app_context()
    try:  # 异步存入数据库
        ctx.push()
        order_info = taobao_orders.query.filter_by(order_number=order_number).first()
        Logistics = Logistics_Dummy_Send(order_info.order_detail, token)
        Logistics_res = Logistics.validate_tid
        if Logistics_res == True:
            try:
                db.session.query(taobao_orders).filter(taobao_orders.order_number == order_number).update(
                    {"Logistics_log": 'Logistics success'})
                db.session.commit()
            except Exception as e:
                print(e)
        else:
            try:
                db.session.query(taobao_orders).filter(taobao_orders.order_number == order_number).update(
                    {"Logistics_log": Logistics_res})
                db.session.commit()
            except Exception as e:
                print(e)
    except Exception as e:
        print(e)
    finally:
        ctx.pop()


if __name__ == '__main__':
    s = Order_Status('4185620967114397616', 1, 'TbAldscbkkrfnxvafksu9yc25n7rrz9bkgxvuh6yb28nudzfxap')
    s.tidInfo('4185620967114397616')
